import React, { FC, useState } from 'react';
import { connect } from 'dva';
import { Form, Input, message, Modal, Space, Switch } from 'antd';
import { CheckOutlined, CloseOutlined } from '@ant-design/icons';
import { addMenu, updateMenu } from '../service';
import { IMenu } from '../data';
import { Dispatch } from 'umi';
import { ModelState } from '../model';

export interface AddMenuProps {
    item: IMenu;
    dispatch: Dispatch;
    visible: boolean;
    close: () => any;
    action: string;
}
export type PartialMenu = Partial<IMenu>

const layout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 16 },
};

const AddMenu: FC<AddMenuProps> = ({ item, dispatch, visible, close, action }) => {
    const add = async () => {
        let res;
        if (action === 'add') {
            console.log(item);
            res = await addMenu(item);
        } else {
            res = await updateMenu(item);
        }

        let content = action === 'add' ? '添加成功' : '修改成功';
        if (res.code === 200) {
            message.success({ content });
            close();
            dispatch({
                type: 'menu/fetchList',
            });
        }
    };

    const handleValueChange = (data:PartialMenu) => {
        setItem(data);
    };

    const setItem = (data:PartialMenu) => {
        return dispatch({
            type: 'menu/setItem',
            payload: { ...item, ...data },
        });
    };

    return (
        <>
            <Modal
                title={action === 'add' ? '添加菜单' : '编辑菜单'}
                destroyOnClose
                visible={visible}
                onOk={add}
                onCancel={() => close()}
                maskClosable={false}
            >
                <Form {...layout} onValuesChange={handleValueChange} initialValues={item}>
                    <Form.Item label="菜单名称" name="name">
                        <Input />
                    </Form.Item>
                    <Form.Item label="父级菜单" name="pName">
                        <Input disabled />
                    </Form.Item>
                    <Form.Item label="路由路径" name="path">
                        <Input />
                    </Form.Item>
                    <Form.Item label="状态" name="forbidden">
                        <Space>
                            <Switch
                                checked={Boolean(item?.forbidden)}
                                checkedChildren={<CheckOutlined />}
                                unCheckedChildren={<CloseOutlined />}
                            ></Switch>
                            <span>已开启</span>
                            <span style={{ color: 'red' }}>已禁用</span>
                        </Space>
                    </Form.Item>
                </Form>
            </Modal>
        </>
    );
};

const mapStateToProps = ({ menu }:{menu:ModelState}) => {
    console.log('object',menu);
    return ({ item: menu.item })
};

export default connect(mapStateToProps)(AddMenu);
